import dateFormat from 'dateformat';

export default function(logger,options) {
  if (!logger || !logger.methodFactory)
    throw new Error('loglevel instance has to be specified in order to be extended')

  var _logger          = logger,
    _url             = options && options.url || 'http://localhost:8080/main/log',
    _callOriginal    = options && options.callOriginal || false,
    _originalFactory = _logger.methodFactory,
    _sendQueue       = [],
    _isSending       = false

  _logger.methodFactory = function (methodName, logLevel) {
    var rawMethod = _originalFactory(methodName, logLevel)

    return function (message) {
      var messages = ['[' + dateFormat(new Date(), 'yyyy/mm/dd HH:MM:ss') + ']', methodName + ':'];
      for (var i = 0; i < arguments.length; i++) {
        messages.push(arguments[i]);
      }
      messages.push('\n');
      message = messages.join(' ');

      if (_callOriginal)
        rawMethod(message)

      _sendQueue.push(message)
      _sendNextMessage()
    }
  }
  _logger.setLevel(_logger.levels.WARN)

  var _sendNextMessage = function(){
    if (!_sendQueue.length || _isSending)
      return

    _isSending = true

    var msg = _sendQueue.shift(),
      req = new XMLHttpRequest()

    req.open("POST", _url, true)
    req.setRequestHeader('Content-Type', 'text/plain')
    req.onreadystatechange = function() {
      if(req.readyState == 4)
      {
        _isSending = false
        setTimeout(_sendNextMessage, 0)
      }
    }
    req.send(msg)
  }
}
